package com.lw.client;

import com.lw.common.Message;
import com.lw.common.MessageType;
import com.lw.common.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 登录验证和用户注册等功能
 */
public class UserClientService {

    private User user;
    private Socket socket;

    /**
     * 验证登录用户是否合法
     *
     * @param userId
     * @param pwd
     * @return
     */
    public boolean checkUser(String userId, String pwd) throws IOException, ClassNotFoundException {
        user = new User(userId, pwd);
        //连接服务器，发送user对象
        socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
        ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
        outputStream.writeObject(user);

        //读取从服务器回复的Message对象
        ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
        Object obj = inputStream.readObject();
        if (obj instanceof Message msg) {
            if (MessageType.MESSAGE_LOGIN_SUCCESSED.equals(msg.getMsgType())) {
                //创建一个和服务器端保持通信的线程
                ClientConnectServerThread clientConnectServerThread = new ClientConnectServerThread(socket);
                clientConnectServerThread.start();

                //放入线程池中方便管理
                ManageClientConnectServerThread.addClientConnectServerThread(userId, clientConnectServerThread);

                return true;
            }
        }
        socket.close();//线程启动失败，关闭socket

        return false;
    }


    /**
     * 请求在线用户列表
     */
    public void onlineFriendList() {
        Message message = new Message();
        message.setSender(user.getUserId());
        message.setMsgType(MessageType.MESSAGE_GET_ONLINE_FRIEND);

        try {
            //获取线程中的socket输出流
            Socket threadSocket = ManageClientConnectServerThread.getClientConnectServerThread(user.getUserId()).getSocket();
            ObjectOutputStream outputStream = new ObjectOutputStream(threadSocket.getOutputStream());
            outputStream.writeObject(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用户退出
     */
    public void logout(){
        Message message = new Message();
        message.setSender(user.getUserId());
        message.setMsgType(MessageType.MESSAGE_CLIENT_EXIT);

        try {
            //获取线程中的socket输出流
            ClientConnectServerThread thread = ManageClientConnectServerThread.getClientConnectServerThread(user.getUserId());
            Socket threadSocket = thread.getSocket();
            ObjectOutputStream outputStream = new ObjectOutputStream(threadSocket.getOutputStream());
            outputStream.writeObject(message);

            System.exit(0);//正常退出系统
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
